package motionsApp.client.randomization;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import motionsApp.client.MotionsChangedCallback;
import motionsApp.client.MotionsRepository;
import motionsApp.shared.MotionDTO;

import com.google.gwt.user.client.ui.HasWidgets;

public class MotionRandomizer implements MotionsChangedCallback, MotionRequestedCallback {

	final private RandomMotionPainter painter;
	final private Random random;
	private List<MotionDTO> motions = new ArrayList<MotionDTO>();

	public MotionRandomizer(MotionsRepository repository, HasWidgets panel) {
		this.painter = new RandomMotionPainter(panel, this);
		this.random = new Random();
		repository.registerListener(this);
	}

	@Override
	public void onChange(List<MotionDTO> motions) {
		this.motions = motions;
		showNewMotion();
		
	}

	private void showNewMotion() {
		if(motions.size() == 0) {
			painter.setMotion("System has no motions");
			return;
		}
		
		int randomMotionIndex = random.nextInt(motions.size());
		painter.setMotion(motions.get(randomMotionIndex).getName());
	}

	@Override
	public void newMotionRequested() {
		showNewMotion();		
	}
}
